﻿#include "msgserver.h"
#include <QDataStream>

MsgServer::MsgServer(QObject *parent) : QObject(parent)
{
    m_tcpServer = new QTcpServer(this);
    connect(m_tcpServer, SIGNAL(newConnection()),
            this, SLOT(slotNewConnection()));

    m_tcpServer->listen(QHostAddress::Any, 55555);
    m_msgProcess = new MsgProcess();
    connect(m_msgProcess, SIGNAL(signalSendMsgToClient(QString,QString)),
            this, SLOT(slotSendMsgToClient(QString,QString)));
    m_msgProcess->start();
}

void MsgServer::slotNewConnection()
{
    qDebug() << "MsgServer::slotNewConnection()";
    QTcpSocket *socket = m_tcpServer->nextPendingConnection();
    m_msgSocket = new MsgSocket(socket);
}

void MsgServer::slotSendMsgToClient(QString id,QString msg)
{
    //找到对应id 的ip 后发送msg
    m_msgSocket->m_tcpSocket->write("ghg");
}

//    connect(m_msgSocket, SIGNAL(signalRegisterSocket(QString,MsgSocket*)),
//            this, SLOT(slotRegisterSocket(QString,MsgSocket*)));
//    connect(m_msgSocket, SIGNAL(signalLogoutSocket(QString,MsgSocket*)),
//            this, SLOT(slotLogoutSocket(QString,MsgSocket*)));
/////???疑问之一 --- socket在堆中 --- 如何释放，何时
//void MsgServer::slotRegisterSocket(QString id, MsgSocket *socket)//保存新连接到map中
//{
//    m_socketMap.insert(id,socket);//登录成功，添加Socket到m_socketMap
//}

//void MsgServer::slotLogoutSocket(QString id, MsgSocket *socket)//从map中删除断开的连接
//{
//    if(m_socketMap.contains(id))
//    {
//        m_socketMap.remove(id);
//    }
//}


